package top.jacktgq.candychat.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author CandyWall
 * @Date 2021/2/25--7:57
 * @Description 接收不到客户端心跳事件的Handler
 *                  继承SimpleChannelInboundHandler的父类ChannelInboundHandlerAdapter
 *                  从而不用实现channelRead0()方法
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 判断是否是IdleStateEvent事件（用于触发用户事件，包含读空闲，写空闲，读写空闲）
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.println("进入读空闲...");
            } else if (event.state() == IdleState.WRITER_IDLE) {
                System.out.println("进入写空闲...");
            } else if (event.state() == IdleState.ALL_IDLE) {
                System.out.println("进入读写空闲...关闭连接");
                System.out.println("channel关闭前，users的数量的为：" + ChatHandler.userChannelGroup.size());
                ctx.channel().close();
                System.out.println("channel关闭后，users的数量的为：" + ChatHandler.userChannelGroup.size());
            }
        }
    }
}
